<template>
  <el-drawer
    v-model="dialogVisible"
    title="自然语言生成SQL"
    size="90%"
    :close-on-click-modal="false"
    :before-close="handleClose"
    direction="rtl"
    :with-header="false"
  >
    <div class="generate-drawer-content">
      <!-- 标题和连接状态显示 -->
      <div class="drawer-header">
        <div class="drawer-title">自然语言生成SQL</div>
        <div class="drawer-header-right">
          <div class="connection-status" :class="{ connected: isConnected }">
            <el-icon class="status-icon"><Connection /></el-icon>
            {{ isConnected ? 'AI 服务已连接' : '正在连接 AI 服务...' }}
          </div>
          <el-button
            class="close-button"
            type="text"
            @click="handleClose"
            :disabled="isGenerating || isLoadingTableColumns"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 主要内容区域 - 左右布局 -->
      <div class="main-content-layout">
        <!-- 左侧 - 数据库信息 -->
        <div class="left-panel">
          <!-- 数据库信息 -->
          <div class="db-info-section" v-if="databaseTables.length > 0">
            <div class="section-title">
              <el-icon><DataAnalysis /></el-icon>
              数据库信息
              <!-- 添加表筛选搜索框 -->
              <div class="table-search">
                <el-input
                  v-model="tableSearchKeyword"
                  placeholder="搜索表名..."
                  prefix-icon="Search"
                  clearable
                  size="small"
                />
              </div>
            </div>
            <div class="db-tips">
              <el-alert
                type="info"
                :closable="false"
                show-icon
              >
                <template #title>
                  单击表名选择/取消选择，双击表名插入到查询需求，点击<el-icon class="view-icon"><View /></el-icon>查看列信息
                </template>
              </el-alert>
            </div>
            <div class="db-info-content">
              <div 
                v-for="table in filteredDatabaseTables" 
                :key="table.name" 
                class="table-item"
                @click="toggleTableSelection(table)"
                @dblclick="insertTableToQuery(table.name)"
                :class="{ 
                  'active-table': selectedTables.includes(table.name),
                  'loading-columns': loadingColumns && currentViewTable === table.name
                }"
              >
                <div class="table-name">
                  {{ table.name }}
                  <el-tooltip v-if="table.comment" :content="table.comment" placement="top">
                    <el-icon class="info-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                  <el-tooltip v-if="table.columnsLoaded" content="已加载列信息" placement="top">
                    <el-icon class="loaded-icon"><Check /></el-icon>
                  </el-tooltip>
                </div>
                <div class="table-actions">
                  <el-button
                    type="primary"
                    size="small"
                    circle
                    @click.stop="showColumnsDialog(table)"
                    :loading="loadingColumns && currentViewTable === table.name"
                  >
                    <el-icon><View /></el-icon>
                  </el-button>
                </div>
              </div>
              <div v-if="filteredDatabaseTables.length === 0" class="empty-tables">
                没有匹配的表
              </div>
            </div>
            
            <!-- 已选择的表 -->
            <div class="selected-tables-section" v-if="selectedTables.length > 0">
              <div class="section-title">
                <span>已选择的表 ({{ selectedTables.length }})</span>
                <el-button type="danger" size="small" @click="clearSelectedTables" plain>
                  清空选择
                </el-button>
              </div>
              <div class="selected-tables-content">
                <el-tag
                  v-for="tableName in selectedTables"
                  :key="tableName"
                  closable
                  @close="removeSelectedTable(tableName)"
                  class="selected-table-tag"
                  :type="getTableColumnsLoadedStatus(tableName) ? 'success' : 'info'"
                >
                  {{ tableName }}
                  <el-icon v-if="!getTableColumnsLoadedStatus(tableName)" class="loading-icon"><Loading /></el-icon>
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧 - 生成区域 -->
        <div class="right-panel">
          <div class="input-section">
            <div class="input-header">
              <span class="section-title">
                <el-icon><ChatLineRound /></el-icon>
                查询需求
              </span>
              <!-- 历史记录下拉菜单 -->
              <el-dropdown @command="handleHistorySelect" trigger="click">
                <el-button size="small" type="info" plain>
                  <el-icon><Timer /></el-icon>
                  历史记录
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="(item, index) in historyList"
                      :key="index"
                      :command="item"
                    >
                      <div class="history-item">
                        <span class="history-text">{{ truncateText(item.prompt, 50) }}</span>
                        <span class="history-time">{{ formatTime(item.timestamp) }}</span>
                        <el-icon
                          class="delete-icon"
                          @click.stop="deleteHistory(index)"
                        >
                          <Delete />
                        </el-icon>
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="!historyList.length" disabled>
                      暂无历史记录
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="historyList.length"
                      divided
                      @click.stop="clearHistory"
                    >
                      <el-icon><Delete /></el-icon>
                      清空历史
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>

            <el-input
              v-model="naturalLanguage"
              type="textarea"
              :rows="6"
              placeholder="请输入您的查询需求，例如：查询最近7天的订单数据，包含订单金额大于1000元的记录"
              :disabled="isGenerating || !isConnected"
            />
          </div>

          <!-- 加载表列信息提示 -->
          <div v-if="isLoadingTableColumns && hasTablesWithoutColumns" class="loading-columns-section">
            <el-alert
              type="info"
              :closable="false"
              show-icon
            >
              <template #title>
                <div class="loading-columns-message">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  正在加载表列信息，请稍候...
                </div>
              </template>
            </el-alert>
          </div>

          <!-- 思考过程 -->
          <div v-if="isGenerating || generatingText" class="result-section">
            <div class="result-info">
              <el-tag size="small" type="info">生成过程</el-tag>
            </div>
            <div class="reasoning-content" ref="reasoningContent" @scroll="handleScroll">
              <div v-text="generatingText"></div>

              <!-- 滚动到底部按钮 -->
              <div
                v-show="showScrollButton"
                class="scroll-bottom-button"
                @click="scrollToBottom('reasoning')"
              >
                <el-icon><Bottom /></el-icon>
              </div>
            </div>
          </div>

          <!-- 生成结果 -->
          <div v-if="generatedSQL" class="result-section">
            <div class="result-info">
              <el-tag size="small" type="success">生成的SQL</el-tag>
              <el-button-group>
                <el-button size="small" type="primary" @click="useGeneratedSQL">
                  使用此SQL
                </el-button>
                <el-button size="small" @click="handleGenerate">
                  重新生成
                </el-button>
              </el-button-group>
            </div>
            <div class="sql-content" ref="sqlContent">
              <pre><code>{{ generatedSQL }}</code></pre>
            </div>
          </div>

          <div class="drawer-footer">
            <el-button @click="handleClose" :disabled="isGenerating || isLoadingTableColumns">
              取消
            </el-button>
            <el-button
              type="primary"
              @click="handleGenerate"
              :loading="isGenerating || isLoadingTableColumns"
              :disabled="!isConnected || !naturalLanguage"
            >
              生成SQL
            </el-button>
          </div>
        </div>
      </div>

      <!-- 列信息对话框 -->
      <el-dialog
        v-model="columnsDialogVisible"
        :title="`表结构: ${currentViewTable}`"
        width="70%"
      >
        <div class="column-dialog-content">
          <!-- 列筛选搜索框 -->
          <div class="column-search">
            <el-input
              v-model="columnSearchKeyword"
              placeholder="搜索列名..."
              prefix-icon="Search"
              clearable
              size="small"
            />
          </div>
          
          <div class="column-tips">
            <el-alert
              type="info"
              :closable="false"
              show-icon
            >
              <template #title>
                点击列名插入到查询需求
              </template>
            </el-alert>
          </div>
          
          <div class="column-table-wrapper">
            <div v-if="loadingColumns" class="loading-columns-wrapper">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>正在加载列信息...</span>
            </div>
            <el-table v-else :data="filteredTableColumns" size="small" border stripe>
              <el-table-column prop="name" label="列名" width="180">
                <template #default="scope">
                  <span class="clickable-column" @click="insertColumnToQuery(scope.row.name)">
                    {{ scope.row.name }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="comment" label="说明" />
              <el-table-column label="属性" width="100">
                <template #default="scope">
                  <el-tag size="small" type="danger" v-if="scope.row.isPrimary">主键</el-tag>
                  <el-tag size="small" type="warning" v-else-if="scope.row.isForeignKey">外键</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="!loadingColumns && filteredTableColumns.length === 0" class="empty-columns">
              没有匹配的列
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Connection,
  Timer,
  ArrowDown,
  Delete,
  Bottom,
  ChatLineRound,
  DataAnalysis,
  InfoFilled,
  Grid,
  Search,
  View,
  Loading,
  Check,
  Close
} from '@element-plus/icons-vue'
import request from "@/utils/request"

const props = defineProps({
  modelValue: Boolean,
  databaseTables: {
    type: Array,
    default: () => []
  },
  activeCompany: {
    type: String,
    default: ''
  },
  onTablesUpdate: {
    type: Function,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'generated'])

// 状态
const naturalLanguage = ref('')
const generatedSQL = ref('')
const generatingText = ref('')
const isGenerating = ref(false)
const isConnected = ref(false)
let ws = null
let reconnectAttempts = 0
const MAX_RECONNECT_ATTEMPTS = 3

// 添加加载表列信息的状态
const isLoadingTableColumns = ref(false)

// 历史记录
const historyList = ref([])
const MAX_HISTORY = 10

// 引用和状态
const reasoningContent = ref(null)
const showScrollButton = ref(false)
const isAutoScrolling = ref(true)

// 添加选中表相关状态
const selectedTables = ref([])
const currentViewTable = ref('')
const columnsDialogVisible = ref(false)
const selectedTableColumns = ref([])
const loadingColumns = ref(false)

// 添加表搜索关键字
const tableSearchKeyword = ref('')

// 添加列搜索关键字
const columnSearchKeyword = ref('')

// 添加过滤后的数据表计算属性
const filteredDatabaseTables = computed(() => {
  const keyword = tableSearchKeyword.value.toLowerCase().trim()
  if (!keyword) return props.databaseTables
  
  return props.databaseTables.filter(table => 
    table.name.toLowerCase().includes(keyword) || 
    (table.comment && table.comment.toLowerCase().includes(keyword))
  )
})

// 添加过滤后的表列计算属性
const filteredTableColumns = computed(() => {
  const keyword = columnSearchKeyword.value.toLowerCase().trim()
  if (!keyword) return selectedTableColumns.value
  
  return selectedTableColumns.value.filter(column => 
    column.name.toLowerCase().includes(keyword) || 
    (column.type && column.type.toLowerCase().includes(keyword)) ||
    (column.comment && column.comment.toLowerCase().includes(keyword))
  )
})

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 获取表的列信息加载状态
const getTableColumnsLoadedStatus = (tableName) => {
  const table = props.databaseTables.find(t => t.name === tableName)
  return table && table.columnsLoaded
}

// 添加计算属性，检查是否有未加载列信息的表
const hasTablesWithoutColumns = computed(() => {
  const tablesNeedColumns = selectedTables.value.length === 0 
    ? props.databaseTables 
    : props.databaseTables.filter(table => selectedTables.value.includes(table.name))
  
  return tablesNeedColumns.some(table => !table.columnsLoaded)
})

// 初始化 WebSocket 连接
const initWebSocket = () => {
  if (ws?.readyState === WebSocket.OPEN) return

  try {
    ws = new WebSocket('wss://adminstore.saas.nbsaas.com/websocket')

    ws.onopen = () => {
      console.log('WebSocket连接已建立')
      isConnected.value = true
      reconnectAttempts = 0
    }

    ws.onclose = () => {
      console.log('WebSocket连接已关闭')
      isConnected.value = false
      if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttempts++
        setTimeout(initWebSocket, 1000 * reconnectAttempts)
      } else {
        ElMessage.error('AI 服务连接失败，请稍后重试')
      }
    }

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      isConnected.value = false
    }

    ws.onmessage = handleMessage
  } catch (error) {
    console.error('创建WebSocket连接错误:', error)
    isConnected.value = false
  }
}

// 处理WebSocket消息
const handleMessage = (event) => {
  try {
    const data = JSON.parse(event.data)

    if (data.type === 'reply') {
      if (data.messageType === 'reasoning') {
        // 更新思考过程
        window.requestAnimationFrame(() => {
          generatingText.value = (generatingText.value || '') + data.content
          if (isAutoScrolling.value) {
            nextTick(() => scrollToBottom('reasoning'))
          }
        })
      } else if (data.messageType === 'content') {
        if (data.content) {
          // 更新生成的SQL - 流式处理
          window.requestAnimationFrame(() => {
            generatedSQL.value = (generatedSQL.value || '') + data.content
            nextTick(() => scrollToBottom('sql'))
          })
        } else {
          // 生成完成
          isGenerating.value = false
          if (generatedSQL.value) {
            // 提取SQL语句
            const extractedSQL = extractSQLFromContent(generatedSQL.value)
            generatedSQL.value = extractedSQL
            addHistory(naturalLanguage.value, extractedSQL)
          }
        }
      } else if (data.messageType === 'complete') {
        // 生成完成
        isGenerating.value = false
        if (generatedSQL.value) {
          // 提取SQL语句
          const extractedSQL = extractSQLFromContent(generatedSQL.value)
          generatedSQL.value = extractedSQL
          addHistory(naturalLanguage.value, extractedSQL)
        }
      }
    }
  } catch (error) {
    console.error('处理WebSocket消息错误:', error)
  }
}

// 从内容中提取SQL语句
const extractSQLFromContent = (content) => {
  // 尝试提取被```或```sql包裹的SQL代码块
  const codeBlockRegex = /```(?:sql)?([\s\S]*?)```/g
  const matches = [...content.matchAll(codeBlockRegex)]
  
  if (matches.length > 0) {
    // 返回最后一个代码块（通常是最终的SQL）
    return matches[matches.length - 1][1].trim()
  }
  
  // 如果没有代码块标记，尝试查找常见的SQL关键字开头的语句
  const sqlKeywordsRegex = /(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH|MERGE|TRUNCATE)[\s\S]+?(?:;|$)/gi
  const keywordMatches = [...content.matchAll(sqlKeywordsRegex)]
  
  if (keywordMatches.length > 0) {
    // 返回最后一个SQL语句（通常是最终的SQL）
    return keywordMatches[keywordMatches.length - 1][0].trim()
  }
  
  // 如果以上方法都无法提取，返回原始内容
  return content.trim()
}

// 从localStorage加载历史记录
const loadHistory = () => {
  try {
    const saved = localStorage.getItem('nlToSqlHistory')
    if (saved) {
      historyList.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 保存历史记录到localStorage
const saveHistory = () => {
  try {
    localStorage.setItem('nlToSqlHistory', JSON.stringify(historyList.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 添加历史记录
const addHistory = (prompt, sql) => {
  // 检查是否已存在相同的记录
  const isDuplicate = historyList.value.some(item =>
    item.prompt === prompt && item.sql === sql
  )

  // 如果是重复记录，则不保存
  if (isDuplicate) {
    return
  }

  // 添加新记录
  historyList.value.unshift({
    prompt,
    sql,
    timestamp: new Date().toISOString()
  })

  // 限制历史记录数量
  if (historyList.value.length > MAX_HISTORY) {
    historyList.value = historyList.value.slice(0, MAX_HISTORY)
  }

  saveHistory()
}

// 删除单条历史记录
const deleteHistory = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除这条历史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    historyList.value.splice(index, 1)
    saveHistory()
    ElMessage.success('已删除历史记录')
  } catch (error) {
    // 用户取消删除
  }
}

// 清空历史记录
const clearHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有历史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    historyList.value = []
    saveHistory()
    ElMessage.success('已清空历史记录')
  } catch (error) {
    // 用户取消清空
  }
}

// 处理历史记录选择
const handleHistorySelect = (item) => {
  naturalLanguage.value = item.prompt
  if (item.sql) {
    generatedSQL.value = item.sql
  }
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 格式化时间
const formatTime = (isoString) => {
  try {
    const date = new Date(isoString)
    return date.toLocaleString()
  } catch (error) {
    return isoString
  }
}

// 处理滚动
const handleScroll = (event) => {
  if (!reasoningContent.value) return

  const { scrollTop, scrollHeight, clientHeight } = reasoningContent.value
  // 如果用户手动滚动，停止自动滚动
  isAutoScrolling.value = scrollHeight - scrollTop - clientHeight < 50
  // 如果离底部超过100px就显示按钮
  showScrollButton.value = scrollHeight - scrollTop - clientHeight > 100
}

// 滚动到底部
const scrollToBottom = (type) => {
  nextTick(() => {
    if (type === 'reasoning' && reasoningContent.value) {
      reasoningContent.value.scrollTop = reasoningContent.value.scrollHeight
      isAutoScrolling.value = true
    } else if (type === 'sql' && sqlContent.value) {
      sqlContent.value.scrollTop = sqlContent.value.scrollHeight
    }
  })
}

// 切换表选择状态
const toggleTableSelection = (table) => {
  const index = selectedTables.value.indexOf(table.name)
  if (index === -1) {
    // 添加到选中列表
    selectedTables.value.push(table.name)
  } else {
    // 从选中列表移除
    selectedTables.value.splice(index, 1)
  }
}

// 移除选中的表
const removeSelectedTable = (tableName) => {
  const index = selectedTables.value.indexOf(tableName)
  if (index !== -1) {
    selectedTables.value.splice(index, 1)
  }
}

// 清空选中的表
const clearSelectedTables = () => {
  selectedTables.value = []
}

// 显示列信息对话框
const showColumnsDialog = async (table) => {
  currentViewTable.value = table.name
  columnSearchKeyword.value = ''
  columnsDialogVisible.value = true
  
  // 加载列信息
  await loadTableColumns(table)
}

// 加载表的列信息
const loadTableColumns = async (table) => {
  // 如果表的列信息已加载，直接返回
  if (table.columnsLoaded && table.columns) {
    selectedTableColumns.value = table.columns
    return
  }
  
  // 设置加载状态
  loadingColumns.value = true
  currentViewTable.value = table.name
  
  try {
    // 查找表在数据库表数组中的索引
    const tableIndex = props.databaseTables.findIndex(t => t.name === table.name)
    if (tableIndex === -1) return
    
    // 如果已经有列信息，直接使用
    if (props.databaseTables[tableIndex].columnsLoaded) {
      selectedTableColumns.value = props.databaseTables[tableIndex].columns
      return
    }
    
    // 否则发送请求获取列信息
    let config = {}
    let headers = {}
    headers.tenant = props.activeCompany
    config.headers = headers
    
    let param = {}
    param.model = "column_list"
    param.filters = {}
    param.filters.db = props.activeCompany
    param.filters.table = table.name
    
    const res = await request.post("/data/list", param, config)
    
    if (res.code === 200 && res.data) {
      // 更新表的列信息
      const columns = res.data.map(col => ({
        name: col.columnName || col.name,
        type: col.dataType || col.datetime,
        comment: col.columnComment || col.comment || '',
        isPrimary: col.isPrimary === true,
        isForeignKey: col.isForeignKey === true,
        nullable: col.nullable === true
      }))
      
      // 更新组件内的状态
      selectedTableColumns.value = columns
      
      // 更新父组件中的数据
      if (tableIndex !== -1) {
        // 使用扩展运算符创建新对象，避免直接修改props
        const updatedTable = {
          ...props.databaseTables[tableIndex],
          columns: columns,
          columnsLoaded: true,
          loadingColumns: false
        }
        
        // 创建新数组并替换修改的项
        const updatedTables = [...props.databaseTables]
        updatedTables[tableIndex] = updatedTable
        
        // 如果父组件提供了更新方法，调用它
        if (typeof props.onTablesUpdate === 'function') {
          props.onTablesUpdate(updatedTables)
        }
      }
    } else {
      ElMessage.error(res.msg || `获取表 ${table.name} 的列信息失败`)
    }
  } catch (error) {
    console.error(`获取表 ${table.name} 的列信息失败:`, error)
    ElMessage.error(`获取表 ${table.name} 的列信息失败`)
  } finally {
    // 重置加载状态
    loadingColumns.value = false
    // 如果是在生成SQL过程中加载的，不需要重置当前查看的表
    if (!isLoadingTableColumns.value) {
      currentViewTable.value = ''
    }
  }
}

// 修改插入列名到查询需求文本框
const insertColumnToQuery = (columnName) => {
  // 获取当前光标位置
  const textarea = document.querySelector('.input-section textarea')
  if (!textarea) return
  
  const cursorPos = textarea.selectionStart
  const textBefore = naturalLanguage.value.substring(0, cursorPos)
  const textAfter = naturalLanguage.value.substring(cursorPos)
  
  // 在光标位置插入列名
  naturalLanguage.value = `${textBefore}${currentViewTable.value}.${columnName}${textAfter}`
  
  // 设置新的光标位置
  nextTick(() => {
    textarea.focus()
    const newCursorPos = cursorPos + currentViewTable.value.length + columnName.length + 1
    textarea.setSelectionRange(newCursorPos, newCursorPos)
  })
  
  ElMessage.success(`已插入列 ${currentViewTable.value}.${columnName}`)
}

// 插入表名到查询需求文本框
const insertTableToQuery = (tableName) => {
  // 获取当前光标位置
  const textarea = document.querySelector('.input-section textarea')
  if (!textarea) return
  
  const cursorPos = textarea.selectionStart
  const textBefore = naturalLanguage.value.substring(0, cursorPos)
  const textAfter = naturalLanguage.value.substring(cursorPos)
  
  // 在光标位置插入表名
  naturalLanguage.value = `${textBefore}${tableName}${textAfter}`
  
  // 设置新的光标位置
  nextTick(() => {
    textarea.focus()
    const newCursorPos = cursorPos + tableName.length
    textarea.setSelectionRange(newCursorPos, newCursorPos)
  })
  
  ElMessage.success(`已插入表 ${tableName}`)
}

// 生成SQL
const handleGenerate = async () => {
  if (!naturalLanguage.value.trim()) {
    ElMessage.warning('请输入查询需求')
    return
  }

  if (!isConnected.value) {
    ElMessage.warning('AI 服务未连接，请稍后重试')
    return
  }

  // 检查是否需要加载表列信息
  const tablesNeedColumns = selectedTables.value.length === 0 
    ? props.databaseTables 
    : props.databaseTables.filter(table => selectedTables.value.includes(table.name))
  
  const tablesWithoutColumns = tablesNeedColumns.filter(table => !table.columnsLoaded)
  
  // 如果有表没有加载列信息，先加载列信息
  if (tablesWithoutColumns.length > 0) {
    isLoadingTableColumns.value = true
    
    try {
      // 依次加载所有表的列信息
      for (const table of tablesWithoutColumns) {
        await loadTableColumns(table)
      }
      
      ElMessage.success('已加载所有表的列信息')
    } catch (error) {
      console.error('加载表列信息失败:', error)
      ElMessage.error('加载表列信息失败，请重试')
      isLoadingTableColumns.value = false
      return
    }
    
    isLoadingTableColumns.value = false
  } else if (tablesNeedColumns.length > 0) {
    // 所有需要的表的列信息已加载
    console.log('所有表的列信息已加载，可以直接生成SQL')
  }

  isGenerating.value = true
  generatingText.value = ''
  generatedSQL.value = ''

  // 准备数据库表结构信息
  const dbInfo = {
    tables: props.databaseTables
      .filter(table => selectedTables.value.length === 0 || selectedTables.value.includes(table.name))
      .map(table => ({
        name: table.name,
        comment: table.comment || '',
        columns: table.columnsLoaded ? table.columns.map(col => ({
          name: col.name,
          type: col.type,
          comment: col.comment || '',
          isPrimary: col.isPrimary,
          isForeignKey: col.isForeignKey
        })) : []
      }))
  }

  // 发送请求
  const message = {
    type: 'prompt',
    message: `我需要根据以下数据库结构生成SQL查询：\n\n${JSON.stringify(dbInfo, null, 2)}\n\n用户需求：${naturalLanguage.value}\n\n请生成符合需求的SQL查询语句。`,
    stream: true // 添加流式处理标志
  }

  try {
    console.info('发送消息:', message)
    ws.send(JSON.stringify(message))
  } catch (error) {
    console.error('发送消息错误:', error)
    isGenerating.value = false
    ElMessage.error('发送请求失败，请重试')
  }
}

// 使用生成的SQL
const useGeneratedSQL = () => {
  if (!generatedSQL.value) return

  // 确保只提取SQL语句
  const sqlToUse = extractSQLFromContent(generatedSQL.value)
  
  emit('generated', sqlToUse)
  handleClose()
  ElMessage.success('已应用生成的SQL')
}

// 关闭对话框
const handleClose = () => {
  if (isGenerating.value) {
    ElMessageBox.confirm('正在生成SQL，确定要取消吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      isGenerating.value = false
      dialogVisible.value = false
    }).catch(() => {})
    return
  }

  dialogVisible.value = false
}

// 组件挂载时
onMounted(() => {
  initWebSocket()
  loadHistory()
})

// 组件卸载时
onUnmounted(() => {
  if (ws) {
    ws.close()
    ws = null
  }
})

// 监听对话框可见性变化
watch(() => dialogVisible.value, (newVal) => {
  if (newVal) {
    // 对话框打开时
    if (!isConnected.value) {
      initWebSocket()
    }
    // 重置搜索关键字和选中的表
    tableSearchKeyword.value = ''
    columnSearchKeyword.value = ''
    selectedTables.value = []
    selectedTableColumns.value = []
    columnsDialogVisible.value = false
  }
})
</script>

<style scoped>
.generate-drawer-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  padding: 0;
  box-sizing: border-box;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.drawer-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.drawer-header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.close-button {
  font-size: 20px;
  color: #909399;
  transition: color 0.3s;
}

.close-button:hover {
  color: #409eff;
}

.close-button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 添加左右布局样式 */
.main-content-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0; /* 修复Flex布局在抽屉中的问题 */
  overflow: hidden; /* 防止内容溢出 */
  padding: 0 20px 20px;
}

.left-panel {
  width: 25%;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.connection-status.connected {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-icon {
  animation: pulse 2s infinite;
}

.connected .status-icon {
  animation: none;
}

.db-info-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  margin-bottom: 12px;
  flex-wrap: wrap;
  justify-content: space-between;
}

.table-search {
  flex: 1;
  max-width: 200px;
  margin-left: auto;
}

.db-info-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow-y: auto;
  flex: 1;
}

.empty-tables {
  width: 100%;
  text-align: center;
  color: #909399;
  padding: 10px;
  font-style: italic;
}

.table-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.table-item:hover {
  border-color: #c6e2ff;
  background-color: #f5f7fa;
}

.table-item.active-table {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.table-item.loading-columns {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

.table-name {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.table-actions {
  display: flex;
  gap: 4px;
}

.view-icon {
  font-size: 14px;
  margin: 0 2px;
  color: #409eff;
}

.selected-tables-section {
  margin-top: 16px;
  border-top: 1px dashed #dcdfe6;
  padding-top: 16px;
}

.selected-tables-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.selected-table-tag {
  margin-right: 0;
}

.column-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.column-search {
  max-width: 300px;
}

.column-table-wrapper {
  margin-top: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 200px;
}

.result-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.reasoning-content {
  padding: 16px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.5;
  color: #606266;
  position: relative;
  flex: 1;
}

.sql-content {
  padding: 16px;
  overflow-y: auto;
  background-color: #f5f7fa;
  flex: 1;
}

.sql-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: monospace;
}

.scroll-bottom-button {
  position: sticky;
  bottom: 16px;
  right: 16px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  float: right;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.history-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.delete-icon {
  color: #f56c6c;
  cursor: pointer;
}

.column-info-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
}

.column-info-content {
  margin-top: 12px;
}

.empty-columns {
  width: 100%;
  text-align: center;
  color: #909399;
  padding: 10px;
  font-style: italic;
  margin-top: 10px;
}

.clickable-column {
  cursor: pointer;
  color: #409eff;
  transition: all 0.3s;
}

.clickable-column:hover {
  text-decoration: underline;
}

@keyframes pulse {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

.db-tips, .column-tips {
  margin-bottom: 10px;
}

.db-tips :deep(.el-alert), .column-tips :deep(.el-alert) {
  padding: 6px 10px;
}

.db-tips :deep(.el-alert__title), .column-tips :deep(.el-alert__title) {
  font-size: 12px;
}

.info-icon {
  font-size: 12px;
  color: #909399;
}

.table-item.active-table .info-icon {
  color: #409eff;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .main-content-layout {
    flex-direction: column;
  }
  
  .left-panel {
    width: 100%;
    min-width: auto;
    max-height: 300px;
  }
}

.loading-columns-section {
  margin-bottom: 16px;
}

.loading-columns-message {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-icon {
  animation: rotate 1.5s linear infinite;
}

.loaded-icon {
  color: #67c23a;
  margin-left: 4px;
  font-size: 12px;
}

.loading-columns-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
  gap: 16px;
}

.loading-columns-wrapper .loading-icon {
  font-size: 24px;
}

.table-item.loading-columns {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
